package com.dashan.servlets;

import static com.dashan.Constants.FRIENDNAME;
import static com.dashan.Constants.USERNAME;
import static com.dashan.servlets.Parameter.Option.Optional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;

import javax.jdo.JDOObjectNotFoundException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.dashan.backend.datastore.DsUser;
import com.dashan.backend.datastore.UserDao;
import com.dashan.backend.util.XmlHelper;

@SuppressWarnings("serial")
public class GetUserServlet extends DashanPrivateServlet {

    @Override
    public ArrayList<Parameter> getParameterList() {
        ArrayList<Parameter> res = super.getParameterList();
        res.add(new Parameter(FRIENDNAME, Optional, String.class));
        return res;
    }
    
    @Override
    public String getUrlPattern() {
        return "/getuser";
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        
        TreeMap<String, Parameter> params = loadParamters(req);
        UserDao dao = new UserDao();
        try {
            DsUser user = dao.getUser(params.get(USERNAME).stringValue());
            DsUser profileUser = null;
            if (params.get(FRIENDNAME).hasValue()) {
                DsUser friend = dao.getUser(params.get(FRIENDNAME).stringValue());
                profileUser = friend;
            } else {
                profileUser = user;
            }

            Document xmlDoc = XmlHelper.createXmlDocument("response");
            Element userEle = profileUser.getXmlElement(xmlDoc);
            Element ele = xmlDoc.createElement("gender");
            ele.appendChild(xmlDoc.createTextNode(profileUser.getProfile().getGender().getName()));
            userEle.appendChild(ele);
            xmlDoc.getDocumentElement().appendChild(userEle);
            resp.getWriter().print(XmlHelper.xml2String(xmlDoc));
        } catch (JDOObjectNotFoundException e) {
            throw new ServletException("User not found: " + e.getMessage());
        } finally {
            dao.commit();
        }
    }
}
